import { useBoolean } from 'ahooks';
import { Form, Input, InputNumber, message, Modal } from 'antd';
import React, { useCallback } from 'react';
import request from '@/utils/request';
import { GlobalFormLayout } from '@/layouts/Form';
import CatalogTreeSelect from '@/components/CatalogTreeSelect';

function collectKeys(nodes, keys) {
  nodes.forEach(node => {
    keys.push(node.catalogId);
    collectKeys(node.children, keys);
  });
}

function findAllChildrenKeys(catalogId, nodeList) {
  const childrenKeys = [];
  const self = nodeList.find(node => node.catalogId === catalogId);
  collectKeys(self.children, childrenKeys);
  return [catalogId, ...childrenKeys];
}

function CatalogEditModal({ code, visible, onClose, data = {}, form, onOk }) {
  const { getFieldDecorator, validateFields } = form;
  const { catalogId, parentCatalogId, title: catalogTitle, sort } = data;
  const [submitting, { setTrue: onSubmitting, setFalse: finishSubmit }] = useBoolean(false);
  const isEdit = !!catalogId;

  const handleSubmit = () => {
    validateFields((err, data) => {
      if (!err) {
        onSubmitting();
        if (isEdit) {
          request
            .post(`/${code}/updateCatalog`, { data })
            .then(() => {
              message.success('修改成功');
              onClose();
              onOk();
            })
            .finally(() => {
              finishSubmit();
            });
        } else {
          request
            .post(`/${code}/createCatalog`, { data })
            .then(() => {
              message.success('创建成功');
              onClose();
              onOk();
            })
            .finally(() => {
              finishSubmit();
            });
        }
      }
    });
  };

  return (
    <Modal
      title={isEdit ? '修改目录' : '新增目录'}
      visible={visible}
      onCancel={onClose}
      destroyOnClose
      confirmLoading={submitting}
      onOk={() => handleSubmit()}
    >
      <Form {...GlobalFormLayout}>
        {catalogId ? (
          <Form.Item>
            {getFieldDecorator('catalogId', {
              initialValue: catalogId,
            })(<Input hidden />)}
          </Form.Item>
        ) : null}
        <Form.Item label="上级目录">
          {getFieldDecorator('parentCatalogId', {
            initialValue: parentCatalogId,
          })(
            <CatalogTreeSelect
              code={code}
              disabledKeys={catalogId ? nodeList => findAllChildrenKeys(catalogId, nodeList) : []}
            />
          )}
        </Form.Item>
        <Form.Item label="目录标题">
          {getFieldDecorator('catalogTitle', {
            initialValue: catalogTitle,
            rules: [
              {
                required: true,
                message: '目录标题不能为空',
              },
            ],
          })(<Input placeholder="请输入" onPressEnter={handleSubmit} />)}
        </Form.Item>
        {isEdit && (
          <Form.Item label="排序">
            {getFieldDecorator('sort', {
              initialValue: sort || 0,
              rules: [
                {
                  required: true,
                  message: '排序不能为空',
                },
              ],
            })(<InputNumber placeholder="请输入" min={0} />)}
          </Form.Item>
        )}
      </Form>
    </Modal>
  );
}

export default Form.create()(CatalogEditModal);
